package 面试题16_数值的整数次方.全面但不高效的实现;

/**
 * @Author ：xu_xiaofeng.
 * @Date ：Created in 10:31 2021/2/14
 * @Description：
 */
public class Solution {
    public double myPow(double x, int n) {
        // 处理底数为0，且指数为负的情况
        if (isEqual(x, 0) && n < 0) {
            return -1;
        }

        int absExponent = Math.abs(n);

        double result = powerWithUnsignedExponent(x, absExponent);

        if (n < 0) {
            result = 1.0 / result;
        }

        return result;
    }

    /**
     * @param base
     * @param absExponent
     * @return
     */
    double powerWithUnsignedExponent(double base, int absExponent) {
        double result = 1.0;
        for (int i = 1; i <= absExponent; i++) {
            result *= base;
        }

        return result;

    }


    boolean isEqual(double num_1, double num_2) {
        double minusResult = num_1 - num_2;

        if (Math.abs(minusResult) < 1e-6) {
            return true;
        }
        return false;
    }
}
